tags:
- Cpp
Typename Keyword in C++ (ENG)
template
in Template Parameter ListsThe typename
keyword in C++ is used to introduce type template parameters and template template parameters (since C++17). It serves as an alternative to the class
keyword in this context.
template <typename T>
T add(T a, T b) {
return a + b;
}
// The code above is as the same as:
template <class T>
T add(T a, T b) {
return a + b;
}
In both cases, T
is a type parameter that will be replaced by the actual data type when you call the function.
typename
's Indication of Dependent TypesThe typename
keyword is also used to indicate that a dependent name(often means a class name) is a type. This helps the compiler understand that the name refers to a type, preventing ambiguity. This is particularly useful in templates where the type depends on a template parameter.
#include <iostream>
// Example of a class with a nested type
class Example {
public:
using value_type = int; // Define 'Example::value_type' as 'int'
};
class Example2 {
public:
using value_type = double; // Define 'Example2::value_type' as 'double'
};
template <typename T>
class MyClass {
typename T::value_type member; // 'typename' tells the compiler that 'value_type' is a type inside 'T'
public:
void setMember(typename T::value_type value) {
member = value;
}
typename T::value_type getMember() const {
return member;
}
};
int main() {
MyClass<Example> myObj; // 'Example' has 'value_type' defined as 'int'
MyClass<Example2> myobj2; // 'Example2' has 'value_type' defined as 'double'
return 0;
}